package top.itaso.app.ui.login

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import top.itaso.app.net.dto.LoginDTO
import top.itaso.app.room.entity.UserEntity
import top.itaso.app.room.repository.UserRepository
import top.itaso.lib.alog.ALog
import top.itaso.lib.common.DateTimeUtils
import top.itaso.lib.net.callback.ISuccess
import top.itaso.lib.net.rtf2.NetClient
import java.util.*

/**
 * @Description: 仅用于处理登录页面的业务逻辑
 * @Author itsdf07
 * @E-Mail 923255742@qq.com
 * @Gitee https://gitee.com/itsdf07
 * @Date 2022/1/10
 */
class LoginViewModel(application: Application) : AndroidViewModel(application) {
    private val _loginUser = MutableLiveData<UserEntity>()

    /**
     * 已成功登录过的用户
     */
    val usersExist: LiveData<List<UserEntity>> = UserRepository.getInstance().querys()

    /**
     * 当前登录用户
     *
     * @return
     */
    val loginUser: LiveData<UserEntity>
        get() = _loginUser

    /**
     * 账号密码匹配登录
     *
     * @param loginId 登录账号，邮箱/手机号
     * @param verCode  密码
     * @param isPhone 是否使用手机号登录,true-手机号，false-不是手机号
     */
    fun login(loginId: String, verCode: String, isPhone: Boolean) {
        if ("itaso" == loginId && "itsdf0707." == verCode) {//超级用户，备用账号，可直接登录
            _loginUser.value = UserEntity().apply {
                uid = "itaso"
                userName = "itaso"
                displayName = "叫我ASO"
                this.password = "itsdf0707."
                loginState = 1
            }
            return
        }
        loginEmail(loginId, verCode, isPhone)
    }

    private fun loginEmail(loginId: String, verCode: String, isPhone: Boolean) {
        val loginParams: HashMap<String, Any> = HashMap<String, Any>()
        loginParams["username"] = loginId
        loginParams["vercode"] = verCode
        loginParams["loginType"] = if (isPhone) 1 else 2
        NetClient.create().url("/api/user/login")
            .params(loginParams)
            .success(ISuccess<String> {
                ALog.dTag(TAG, "/api/user/login->response:%s", it)
                val respLoginResultBean = Gson().fromJson(it, LoginDTO::class.java)
                if (respLoginResultBean.status != 200) {
                    _loginUser.value = UserEntity().apply {
                        loginState = respLoginResultBean.status;
                    }
                    return@ISuccess
                }
                val user: UserEntity = UserEntity().apply {
                    uid = respLoginResultBean.data.uid
                    userName = loginId
                    displayName = respLoginResultBean.data.displayName
                    token = respLoginResultBean.data.token
                    this.password = verCode
                    createDate = DateTimeUtils.formatDateTimeStyle(
                        Date().time,
                        DateTimeUtils.FORMAT_YYYYMMDDHHMMSS
                    )
                    loginState = 1
                }
                _loginUser.value = user

                UserRepository.getInstance().insert(user)
            }).error { code, msg ->
                ALog.dTag(TAG, "code:%s,msg:%s", code, msg)
                _loginUser.value = UserEntity().apply {
                    loginState = code;
                }
            }
            .failure {
                _loginUser.value = UserEntity().apply {
                    loginState = 0
                }
            }
            .build().postRaw()
    }

    /**
     * 修改用户信息
     *
     * @param userEntity
     */
    fun modifyUser(userEntity: UserEntity?) {
        val userIndex = UserRepository.getInstance().update(userEntity)
        if (userIndex <= 0) {
            Toast.makeText(getApplication(), "修改失败，请重试", Toast.LENGTH_SHORT).show()
            return
        }
        Toast.makeText(getApplication(), "修改成功", Toast.LENGTH_SHORT).show()
    }

    companion object {
        private val TAG = LoginViewModel::class.java.simpleName
    }

}